package com.yw.common.core.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import com.yw.common.core.db.exception.DBCloseException;
import com.yw.common.core.db.exception.DBCommitException;
import com.yw.common.core.db.exception.DBException;
import com.yw.common.core.db.exception.DBOpenException;
import com.yw.common.core.db.exception.DBOpenTransException;
import com.yw.common.core.db.exception.DBRollBackException;

/**
 * 抽象的数据库连接类型
 * @author aoshiguchen
 * @time 2015-09-10
 */

public abstract class AbstractDBConnection implements IDBConnection{
	protected String driverName;
	protected String dbURL;
	protected String userName;
	protected String userPwd;
	
	protected Connection conn;
	
	public AbstractDBConnection(String driverName,String dbURL,String userName, String userPwd) {
		this.driverName = driverName;
		this.dbURL = dbURL;
		this.userName = userName;
		this.userPwd = userPwd;
	}

	public void close()throws DBCloseException{
		
		try {
			conn.close();
		} catch (SQLException e) {
			throw new DBCloseException("DB Close Failed !");
		}
		
	}

	public Connection open() throws DBOpenException {

		try {
			Class.forName(driverName);
			conn = DriverManager.getConnection(dbURL,userName,userPwd);
			
		} catch (Exception e) {
			throw new DBOpenException("DB Open Failed");
		}		
		 
		return conn;
	}

	public PreparedStatement prepareStatement(String sql) throws DBException {
		PreparedStatement preparedStatement = null;
		
		try {
			preparedStatement = conn.prepareStatement(sql);
		} catch (SQLException e) {
			throw new DBOpenException("DB prepareStatement Failed");
		}
		
		return preparedStatement;
	}

	@Override
	public void commit() throws DBCommitException {
		
		try {
			this.conn.commit();
			this.conn.setAutoCommit(true);
		} catch (SQLException e) {
			throw new DBCommitException("DB commit Failed !");
		}
		
	}

	@Override
	public boolean isClosed() throws DBException {
		boolean res = true;
		
		try{
			res = this.conn.isClosed();
		}catch(SQLException e){
			throw new DBException("DB Check isClosed Failed !");
		}
		
		return res;
	}

	@Override
	public void openTrans() throws DBOpenTransException {
		try {
			this.conn.setAutoCommit(false);
		} catch (SQLException e) {
			throw new DBOpenTransException("DB openTrans Failed !");
		}
		
	}

	@Override
	public void rollBack() throws DBRollBackException {
		
		try {
			this.conn.rollback();
		} catch (SQLException e) {
			throw new DBRollBackException("DB rollBack Failed !");
		}
		
	}
}
